package arbor.mining.util.stock;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.StringTokenizer;

import arbor.mining.util.date.DateUtil;
import arbor.mining.util.net.WebStringConn;
/**
 * StockDataTask is basic class to retrieve TW stock data from DBMaker.
 * @author doug
 *
 */
public class DBMakerGather extends StockDataGather{

	private static DateFormat DBMAKER_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");	

	/**
	 * Get stock history as HLOC list.
	 * The function may require more memory!!! You can set -Xmx1000m in the VM parameter.
	 * @return
	 */
	public ArrayList<StockEntity> getIndexHistory(int indexID) {
		ArrayList<StockEntity> list = new ArrayList<StockEntity>();
		WebStringConn conn = new WebStringConn(null);
		String content = null;
		
		switch (indexID) {
		case ELE1_ID:
			  logger.info("Get "+urlProp.getProperty("ELE1_URL"));
			  content = conn.getAllTableContent(urlProp.getProperty("ELE1_URL"), true,true);
			  break;
		case FIN1_ID:
			  logger.info("Get "+urlProp.getProperty("FIN1_URL"));
			  content = conn.getAllTableContent(urlProp.getProperty("FIN1_URL"), true,true);
			  break;
		case STX1_ID:
			  logger.info("Get "+urlProp.getProperty("STX1_URL"));
			  content = conn.getAllTableContent(urlProp.getProperty("STX1_URL"), true,true);
			  break;
		case WTX0_ID:
			  logger.info("Get "+urlProp.getProperty("WTX0_URL"));
			  content = conn.getAllTableContent(urlProp.getProperty("WTX0_URL"), true,true);
			  break;
		case WTX1_ID:
			  logger.info("Get "+urlProp.getProperty("WTX1_URL"));
			  content = conn.getAllTableContent(urlProp.getProperty("WTX1_URL"), true,true);
			  break;
		default:
			  logger.error("The index ID is not supported\n");
			  break;
		}
        parseHistoryEntity(list, content);
        if (GATHER_DEBUG)
          logger.info("Retrieve "+ list.size()+ " StockEntity data");
        return list;
	}

	public StockEntity getTodayIndexPrice(int indexID) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		StockEntity entity = null;
		WebStringConn conn = new WebStringConn(null);
		logger.info("Get "+urlProp.getProperty("TODAY_INDEX_URL"));
		String dayc = conn.getHTML_by_StringExtractor(urlProp.getProperty("TODAY_INDEX_URL"));
		StringTokenizer token = new StringTokenizer(dayc, "\n");
		token.nextToken();
		String day = token.nextToken();
		try {
			if (df.parse(day.split(": ")[1]).compareTo(
					df.parse(DateUtil.getCurrentDashedDate())) < 0) {
				;
			}
			else {
				String content = conn.getAllTableContent(urlProp.getProperty("TODAY_INDEX_URL"), true,true);
				ArrayList<StockEntity> list = new ArrayList<StockEntity>(); 
				parseTodayEntity(list, content);
				entity = list.get(indexID);
			}
		} catch (ParseException e) {
			logger.error(e);
		}

		return entity;

	}

	public void  parseTodayEntity(ArrayList<StockEntity> list, String content) {
		StringTokenizer token = new StringTokenizer(content,"\n");
		while (token.hasMoreTokens()) {	
			String line = token.nextToken();
		    
		    if (!(line.split(",")[1]).equals("股票名稱")) {
		      token.nextToken();	      
		      
		      Date day = DateUtil.getCurrentDate();
		      GregorianCalendar startTime = new GregorianCalendar();
		      GregorianCalendar endTime = new GregorianCalendar();
		      
			  startTime.setTime(day);
			  startTime.set(Calendar.HOUR_OF_DAY, 9);			  
			  endTime.setTime(day);
			  endTime.set(Calendar.HOUR_OF_DAY, 13);
			  endTime.set(Calendar.MINUTE, 30);
			  
		      StockEntity entity = new StockEntity(StockEntity.RANGE_TYPE_DAY, startTime, endTime);
		      entity.ohlc.open = Double.parseDouble((token.nextToken().split(","))[1]); 		    	
		      entity.ohlc.high = Double.parseDouble((token.nextToken().split(","))[1]);
		      entity.ohlc.low = Double.parseDouble((token.nextToken().split(","))[1]);
		      entity.ohlc.close = Double.parseDouble((token.nextToken().split(","))[1]);
		      token.nextToken();
		      entity.volume = Integer.parseInt((token.nextToken().split(","))[1]);
		      token.nextToken();
		      list.add(entity);
		    }
		    else {
		      /*skip the next five line*/
		      token.nextToken();token.nextToken();token.nextToken();token.nextToken();
		      token.nextToken();token.nextToken();token.nextToken();token.nextToken();
		    }
		}			
	}
	public void parseHistoryEntity(ArrayList<StockEntity> list, String content) {
		/**
		 * Parse the content as HLOC list.
		 */
		StringTokenizer token = new StringTokenizer(content,"\n");
		while (token.hasMoreTokens()) {	
			String line = token.nextToken();
		    
		    if (!(line.split(",")[1]).equals("日期")) {
		      Date day = null;
		      GregorianCalendar startTime = new GregorianCalendar();
		      GregorianCalendar endTime = new GregorianCalendar();
		      try {
		    	  day = DBMAKER_DATE_FORMAT.parse(line.split(",")[1]);
			  } catch (ParseException e) {
				  logger.error(e);
			  } 
			  startTime.setTime(day);
			  startTime.set(Calendar.HOUR_OF_DAY, 9);			  
			  endTime.setTime(day);
			  endTime.set(Calendar.HOUR_OF_DAY, 13);
			  endTime.set(Calendar.MINUTE, 30);
			  
		      StockEntity entity = new StockEntity(StockEntity.RANGE_TYPE_DAY, startTime, endTime);
		      entity.ohlc.open = Double.parseDouble((token.nextToken().split(","))[1]); 		    	
		      entity.ohlc.high = Double.parseDouble((token.nextToken().split(","))[1]);
		      entity.ohlc.low = Double.parseDouble((token.nextToken().split(","))[1]);
		      entity.ohlc.close = Double.parseDouble((token.nextToken().split(","))[1]);
		      entity.volume = Integer.parseInt((token.nextToken().split(","))[1]);
		      list.add(entity);
		    }
		    else {
		      /*skip the next five line*/
		      token.nextToken();token.nextToken();token.nextToken();token.nextToken();token.nextToken();
		    }
		}		
	}
	public static void main(String[] args) {
		DBMakerGather gather = new DBMakerGather();
		gather.getIndexHistory(WTX1_ID);
		gather.getTodayIndexPrice(WTX1_ID);
	}	
}
